package by.yakusekmaxim.bookgid.dataaccess.impl;
import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import by.yakusekmaxim.bookgid.dataaccess.FeedbackDao;
import by.yakusekmaxim.bookgid.datamodel.Book;
import by.yakusekmaxim.bookgid.datamodel.Feedback;
import by.yakusekmaxim.bookgid.datamodel.Feedback_;
import by.yakusekmaxim.bookgid.datamodel.UserAccount;

@Repository
public class FeedbackDaoImpl extends AbstractDaoImpl<Long, Feedback> implements FeedbackDao {

    protected FeedbackDaoImpl() {
        super(Feedback.class);
    }

	@Override
	public List<Feedback> getAllEvaluationsBooks(Book book) {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<Feedback> criteria = cBuilder.createQuery(Feedback.class);
		Root<Feedback> root = criteria.from(Feedback.class);
		criteria.where(cBuilder.equal(root.get(Feedback_.book), book));
		criteria.select(root);

		TypedQuery<Feedback> query = getEm().createQuery(criteria);
		List<Feedback> results = query.getResultList();
		return results;
	}

	@Override
	public List<Feedback> getBookUserEvaluation(Book book, UserAccount User) {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<Feedback> criteria = cBuilder.createQuery(Feedback.class);
		Root<Feedback> root = criteria.from(Feedback.class);
		criteria.where(cBuilder.equal(root.get(Feedback_.book), book),
				cBuilder.equal(root.get(Feedback_.userAccount), User));
		criteria.select(root);

		TypedQuery<Feedback> query = getEm().createQuery(criteria);
		List<Feedback> results = query.getResultList();
		return results;
	}
}
